// 发布订阅模式类
export default class EventEmitter<EventName extends string> {
    private events: { [key: string]: Function[] } = {}
    private allEvents: Function[] = []

    // 订阅某个事件
    on(eventName: EventName, listener: Function): void {
        if (!this.events[eventName]) {
            this.events[eventName] = []
        }
        this.events[eventName].push(listener)
    }

    // 订阅所有事件
    onAll(listener: Function): void {
        this.allEvents.push(listener)
    }

    // 发布事件
    emit(eventName: EventName, ...args: any[]): void {
        if (this.events[eventName]) {
            this.events[eventName].forEach((listener) => listener(...args))
        }
        this.allEvents.forEach((listener) => listener(eventName, ...args))
    }

    // 清空所有事件
    clear(): void {
        this.events = {}
        this.allEvents = []
    }
}